import type { Subscribe, ObserverOrNext } from '../types/Observable'
import { Subscriber } from './Subscriber'
import { pipeFromArray } from './pipeFromArray'
export class Observable {
  _subscribe: any
  constructor(subscribe: Subscribe) {
    if (subscribe) {
      // 如果传入观察函数先进行保存,当外部调用subscribe方法时才会被动发送数据
      this._subscribe = subscribe
    }
  }
  /**
   * 接收一个Observer对象或next处理函数返回Subscriber进行主动触发
   * @param observerOrNext {next?:(v)=>{},error?:(v)=>{},complete:()=>{}} | next:(v)=>{}
   * @returns Subscriber
   */
  subscribe(observerOrNext: ObserverOrNext) {
    // 接收参数,构建Subscriber对象
    const subscriber = new Subscriber(observerOrNext)
    const cancelFn = this._subscribe(subscriber)
    // 如果有返回取消订阅函数追加到数组中，方便调用unsubsribe时调用
    subscriber.add(cancelFn)
    return subscriber
  }
  pipe(...operations: Function[]) {
    // 把老的Observable传递给operation的source参数
    // (this)就是调用source函数传递当前observable
    return pipeFromArray(operations)(this)
  }
}